<template>
  <div class="sold-products-container">
    <!-- 顶部状态筛选 -->
    <el-affix :offset="0">
      <el-tabs 
        v-model="activeStatus" 
        class="status-tabs"
        @tab-change="handleStatusChange"
      >
        <el-tab-pane label="全部" name="全部"></el-tab-pane>
        <el-tab-pane label="待发货" name="待发货"></el-tab-pane>
        <el-tab-pane label="待收货" name="待收货"></el-tab-pane>
        <el-tab-pane label="已完成" name="已完成"></el-tab-pane>
        <el-tab-pane label="已取消" name="已取消"></el-tab-pane>
      </el-tabs>
    </el-affix>

    <!-- 商品列表 -->
    <el-scrollbar class="product-scrollbar" @scroll="handleScroll">
      <div class="product-list">
        <el-card 
          v-for="order in filteredOrders" 
          :key="order.id" 
          class="product-card"
          shadow="hover"
        >
          <div class="product-content">
           <el-image 
  class="product-image" 
  :src="getProductImage(order)"
  fit="cover"
  :loading="true"
>
  <template #placeholder>
    <div class="image-loading">
      <el-icon class="is-loading"><Loading /></el-icon>
    </div>
  </template>
  <template #error>
    <div class="image-error">
      <el-icon><Picture /></el-icon>
    </div>
  </template>
</el-image>
            
            <div class="product-info">
              <div class="product-name">{{ order.product_title }}</div>
              <div class="product-price">¥{{ order.snapshot_price }}</div>
              <div class="product-status">
                <el-tag :type="getStatusType(order.status_display)" size="small">
                  {{ order.status_display }}
                </el-tag>
              </div>
              <div class="action-buttons">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="viewDetails(order.order_code)"
                  class="detail-btn"
                >
                  查看详情
                </el-button>
                <el-button 
                  v-if="order.status_display === '待发货'"
                  type="success" 
                  size="small" 
                  @click="handleShip(order.order_code)"
                  class="ship-btn"
                >
                  发货
                </el-button>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 加载更多 -->
        <div v-if="loading" class="loading-more">
          <el-icon class="is-loading"><Loading /></el-icon>
          <span>加载中...</span>
        </div>
        <div v-if="!hasMore" class="no-more-data">
          没有更多数据了
        </div>
      </div>
    </el-scrollbar>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Picture, Loading } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import apiClient from '@/utils/request'
import { DEFAULT_IMAGE } from '@/utils/orderUtils'  // 添加这行

// 订单数据
const orders = ref([])
const activeStatus = ref('全部')
const currentPage = ref(1)
const itemsPerPage = ref(10)
const loading = ref(false)
const hasMore = ref(true)
const router = useRouter()

// 状态映射
const statusMap = {
  '全部': null,
  '待发货': 1,  // 待发货
  '待收货': 2,  // 待收货
  '已完成': 3,  // 已完成
  '已取消': 5   // 已取消
}

// 过滤后的订单列表
const filteredOrders = computed(() => {
  if (activeStatus.value === '全部') {
    return orders.value.filter(order => 
      order.status_display === '待发货' || 
      order.status_display === '待收货' || 
      order.status_display === '已完成' ||
      order.status_display === '已取消'
    ).slice(0, currentPage.value * itemsPerPage.value)
  } else {
    return orders.value.filter(order => order.status_display === activeStatus.value)
                      .slice(0, currentPage.value * itemsPerPage.value)
  }
})

// 加载订单数据
const loadOrders = async () => {
  try {
    loading.value = true
    const status = statusMap[activeStatus.value]
    const params = { 
      role: 'seller',
      page: currentPage.value,
      ...(status !== null && { status })
    }
    
    const response = await apiClient.get('/api/orders/', { params })
    
    const newOrders = response.data.results || []

    if (currentPage.value === 1) {
      orders.value = newOrders
    } else {
      orders.value = [...orders.value, ...newOrders]
    }

    // 加载每个订单的商品图片
    await Promise.all(orders.value.map(async (order) => {
      await loadProductImage(order)
    }))

    hasMore.value = response.data.next !== null
  } catch (error) {
    console.error('加载订单失败:', error)
    ElMessage.error('加载订单失败')
  } finally {
    loading.value = false
  }
}

// 加载商品图片
const loadProductImage = async (order) => {
  try {
    const response = await apiClient.get(`/api/products/buyer/${order.product_code}/`)
    order.product_image = response.data.images?.[0]?.url || DEFAULT_IMAGE
  } catch (error) {
    console.error(`获取商品 ${order.product_code} 图片失败:`, error)
    order.product_image = DEFAULT_IMAGE
  }
}

// 获取商品图片
const getProductImage = (order) => {
  return order.product_image || DEFAULT_IMAGE
}

// 根据状态获取标签类型
const getStatusType = (status) => {
  const types = {
    '待发货': 'warning',
    '待收货': 'primary',
    '已取消': 'danger',
    '已完成': 'success'
  }
  return types[status] || ''
}

// 状态切换
const handleStatusChange = () => {
  currentPage.value = 1
  loadOrders()
}

// 查看订单详情
const viewDetails = (orderCode) => {
  router.replace({ 
    name: 'ordersDetail', 
    query: {
      from: '/Mine/maichu'  // 明确指定来源
    },
    params: { order_code: orderCode }
  })
}

const handleShip = async (orderCode) => {
  try {
   
    const order = orders.value.find(o => o.order_code === orderCode)
    if (!order) {
      throw new Error('订单不存在')
    }

    // 修正后的请求（使用apiClient并简化参数）
    const response = await apiClient.put(`/api/orders/${orderCode}/`, {
      status: 2, // 交易中(已发货)
      snapshot_price: order.snapshot_price,
      payment_time: order.payment_time
    })
    
    if (response.status === 200) {
      ElMessage.success('发货成功')
      // 刷新当前订单状态
      loadOrders()
    }
  } catch (error) {
    console.error('发货失败:', error)
    ElMessage.error(error.response?.data?.message || '发货失败')
  }
}

// 滚动加载更多
const handleScroll = ({ scrollTop, clientHeight, scrollHeight }) => {
  const isNearBottom = scrollHeight - scrollTop <= clientHeight + 50
  
  if (isNearBottom && !loading.value && hasMore.value) {
    currentPage.value++
    loadOrders()
  }
}

// 初始化加载
onMounted(() => {
  loadOrders()
})
</script>

<style scoped>
.sold-products-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: var(--el-bg-color-page);
}

.status-tabs {
  background-color: var(--el-bg-color);
  padding: 0 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.status-tabs :deep(.el-tabs__header) {
  margin: 0;
}

.status-tabs :deep(.el-tabs__nav-wrap) {
  padding: 0 20px;
}

.product-scrollbar {
  flex: 1;
  padding: 20px;
}

.product-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.product-card {
  transition: all 0.3s;
  border-radius: 8px;
}

.product-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 16px 0 rgba(0, 0, 0, 0.1);
}

.product-content {
  display: flex;
  gap: 15px;
}

.product-image {
  width: 100px;
  height: 100px;
  border-radius: 6px;
  flex-shrink: 0;
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--el-fill-color-light);
  color: var(--el-text-color-placeholder);
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 16px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-price {
  font-size: 18px;
  font-weight: bold;
  color: var(--el-color-primary);
  margin: 8px 0;
}

.product-status {
  margin: 8px 0;
}

.action-buttons {
  display: flex;
  gap: 8px;
  margin-top: 10px;
}

.detail-btn {
  width: 70%;
}

.ship-btn {
  width: 30%;
}

.loading-more {
  grid-column: 1 / -1;
  text-align: center;
  padding: 20px;
  color: var(--el-text-color-secondary);
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
}

.no-more-data {
  grid-column: 1 / -1;
  text-align: center;
  padding: 20px;
  color: var(--el-text-color-secondary);
}
</style>